#!/bin/bash

# set -x 
#bash -c "$(curl -fksSL https://172.20.191.209/wangsong/analyse-problem/-/raw/master/analyse-update-error.sh)"

#bash -c "$(curl -fksSL https://gitee.com/newwangsong/analyse-update/raw/master/analyse-update-error.sh)"

ERROR_DESC_FILE="/var/lib/kylin-system-updater/remain/error-info"
RECORD_PKGS_VERSION=(kylin-system-updater kylin-activation kylin-update-frontend libkylin-activation 
                    ukui-notification-daemon ukui-session-manager)

TRUE=true
FALSE=false

APT_TERM_LOG="/var/log/apt/term.log"
UPDATER_LOG_PATH="/var/log/kylin-system-updater/kylin-system-updater.log.1"

OFFLINE_SOURCE_PATH="/media/OfflineSource"

OFFLINE_SOURCE_FLAG=$FALSE


ERROR_DESC=""
SOURCE_TYPE=""
PUSH_UPDATE_PATCH=""
SOURCES_LIST=""

# 检查是否带有参数
if [[ "$1" == "--output" ]]; then
    OUTPUT_FILE=$TRUE
else
    OUTPUT_FILE=$FALSE
fi

BOLD="$(tput bold 2>/dev/null || printf '')"
GREY="$(tput setaf 0 2>/dev/null || printf '')"
UNDERLINE="$(tput smul 2>/dev/null || printf '')"
RED="$(tput setaf 1 2>/dev/null || printf '')"
GREEN="$(tput setaf 2 2>/dev/null || printf '')"
YELLOW="$(tput setaf 3 2>/dev/null || printf '')"
BLUE="$(tput setaf 4 2>/dev/null || printf '')"
MAGENTA="$(tput setaf 5 2>/dev/null || printf '')"
NO_COLOR="$(tput sgr0 2>/dev/null || printf '')"

info() {
    if [ "$OUTPUT_FILE" = "$TRUE" ]; then
        printf '%s\n\n' "${BOLD}${GREY}>${NO_COLOR} $*" | tee >> $ERROR_DESC_FILE
    else
        printf '%s\n\n' "${BOLD}${GREY}>${NO_COLOR} $*" 
    fi
}

warn() {
    if [ "$OUTPUT_FILE" = "$TRUE" ]; then
        printf '%s\n' "${YELLOW}! $*${NO_COLOR}" | tee >> $ERROR_DESC_FILE
    else
        printf '%s\n' "${YELLOW}! $*${NO_COLOR}"
    fi
}

error() {
    if [ "$OUTPUT_FILE" = "$TRUE" ]; then
        printf '%s\n\n' "${BOLD}> $*${NO_COLOR}" | tee >> $ERROR_DESC_FILE
    else
        printf '%s\n\n' "${BOLD}> $*${NO_COLOR}"
    fi
}

completed() {
  printf '%s\n' "${GREEN}✓${NO_COLOR} $*"
}


# -----------------------------------------------------------------------------
# Make sure everything really stops when CTRL+C is pressed
# -----------------------------------------------------------------------------

fn_terminate_script() {
	exit 1
}
trap 'fn_terminate_script' SIGINT


# 检查推送内容
if [ -f "/var/lib/kylin-software-properties/template/important.list" ]; then
    if [ -s "/var/lib/kylin-software-properties/template/important.list" ]; then
        PUSH_UPDATE_PATCH=$(cat /var/lib/kylin-software-properties/template/important.list)
    else
        PUSH_UPDATE_PATCH=""
    fi
else
    PUSH_UPDATE_PATCH=""
fi

# 检查源信息
if [ -f "/etc/kylin-system-updater/apt_private.conf" ]; then
    SOURCES_LIST="/var/lib/kylin-system-updater/sources.list"
else
    SOURCES_LIST="/etc/apt/sources.list"
fi

if [ -f $SOURCES_LIST ]; then
    # 检查是否使用离线源
    if grep -q "deb file:" "$SOURCES_LIST"; then
        SOURCE_TYPE="离线源更新"
        OFFLINE_SOURCE_FLAG=$TRUE
    else
        SOURCE_TYPE="在线源更新"
    fi
else
    SOURCE_TYPE="在线源更新"
fi

arg_prompt(){
    if [ "$OUTPUT_FILE" = "$TRUE" ]; then
        echo "" > $ERROR_DESC_FILE
        > $ERROR_DESC_FILE
    fi

    # printf "  %s\n" "${UNDERLINE}系统更新基础信息:${NO_COLOR}"
    info "${BOLD}更新方式${NO_COLOR}：  ${GREEN}${SOURCE_TYPE}${NO_COLOR}"
    info "${BOLD}更新内容${NO_COLOR}：  ${GREEN}${PUSH_UPDATE_PATCH}${NO_COLOR}"
    info "${BOLD}更新源${NO_COLOR}：    ${GREEN}${SOURCES_LIST}${NO_COLOR}"
    info "${BOLD}更新错误${NO_COLOR}：  ${GREEN}${ERROR_DESC}${NO_COLOR}"
    error "${BOLD}错误描述${NO_COLOR}：  ${BOLD}${RED}$1${NO_COLOR}"
    error "${BOLD}解决方案${NO_COLOR}：  ${BOLD}${RED}$2${NO_COLOR}"
    if ! [ -z "$3" ]; then
        info "${BOLD}其他描述${NO_COLOR}：  ${GREEN}$3${NO_COLOR}"
    fi

    if ! [[ "$0" == *"/usr/share/kylin-system-updater/scripts/"* ]]; then
        report_updater_log
    fi
    exit 0
}

arg_prompt_not_exit(){
    if [ "$OUTPUT_FILE" = "$TRUE" ]; then
        echo "" > $ERROR_DESC_FILE
        > $ERROR_DESC_FILE
    fi

    # printf "  %s\n" "${UNDERLINE}系统更新基础信息:${NO_COLOR}"
    info "${BOLD}更新方式${NO_COLOR}：  ${GREEN}${SOURCE_TYPE}${NO_COLOR}"
    info "${BOLD}更新内容${NO_COLOR}：  ${GREEN}${PUSH_UPDATE_PATCH}${NO_COLOR}"
    info "${BOLD}更新源${NO_COLOR}：    ${GREEN}${SOURCES_LIST}${NO_COLOR}"
    info "${BOLD}更新错误${NO_COLOR}：  ${GREEN}${ERROR_DESC}${NO_COLOR}"
    error "${BOLD}错误描述${NO_COLOR}：  ${BOLD}${RED}$1${NO_COLOR}"
    error "${BOLD}解决方案${NO_COLOR}：  ${BOLD}${RED}$2${NO_COLOR}"
    if ! [ -z "$3" ]; then
        info "${BOLD}其他描述${NO_COLOR}：  ${GREEN}$3${NO_COLOR}"
    fi

    if ! [[ "$0" == *"/usr/share/kylin-system-updater/scripts/"* ]]; then
        report_updater_log
    fi
    exit 0
}

report_updater_log() {
    cd /tmp
    #建立收集的log目录
    mkdir updaterlog

    date >> updaterlog/base-info

    # 记录包版本
    for pkg in "${RECORD_PKGS_VERSION[@]}"; do
        dpkg -l | grep $pkg >> updaterlog/base-info
    done

    info "${BOLD}正在导出系统更新日志...${NO_COLOR}"

    # 收集当前系统配置
    cp /var/lib/kylin-system-updater/sources.list updaterlog/private-sources.list >/dev/null 2>&1 || true 
    cp /etc/apt/sources.list updaterlog/system-sources.list >/dev/null 2>&1 || true 
    cp -r /etc/apt/apt.conf.d updaterlog >/dev/null 2>&1 || true 
    cp -r /usr/share/kylin-update-desktop-config updaterlog >/dev/null 2>&1 || true 
    cp -r /var/lib/kylin-system-updater/json updaterlog/upgrade-data >/dev/null 2>&1 || true 
    cp -r /var/cache/kylin-system-updater updaterlog/upgrade-data >/dev/null 2>&1 || true 
    cp -r /var/lib/dpkg/status updaterlog >/dev/null 2>&1 || true 

    #收集系统更新的日志
    cp -r /var/log/apt updaterlog >/dev/null 2>&1 || true 
    cp -r /var/log/dpkg.log updaterlog >/dev/null 2>&1 || true 
    cp -r /var/log/kylin-unattended-upgrades updaterlog >/dev/null 2>&1 || true 
    cp -r ~/.config/kylin-background-upgrade updaterlog >/dev/null 2>&1 || true 
    cp -r /var/log/kylin-system-updater/ updaterlog >/dev/null 2>&1 || true 
    cp -r /var/log/syslog updaterlog >/dev/null 2>&1 || true 

    #激活
    mkdir -p updaterlog/kylin-activation
    cp -r ~/.log/kylin-activation/ updaterlog/kylin-activation >/dev/null 2>&1 || true 
    cp /etc/LICENSE updaterlog/kylin-activation >/dev/null 2>&1 || true 
    cp /etc/.kyinfo updaterlog/kylin-activation >/dev/null 2>&1 || true 

    #P2P
    cp -r /var/log/apt-p2p.log updaterlog >/dev/null 2>&1 || true 

    # 源更新管理器
    cp -r /var/log/kylin-software-properties/ updaterlog >/dev/null 2>&1 || true 

    #收集前端日志
    cp -r ~/.log/kylin-update-frontend-notifysend.log updaterlog >/dev/null 2>&1 || true
    cp -r ~/.log/ukui-control-center.log updaterlog >/dev/null 2>&1 || true 
    cp -r ~/.log/ukui-notification-daemon.log updaterlog >/dev/null 2>&1 || true
    cp -r ~/.config/ukui-session/ updaterlog >/dev/null 2>&1 || true
    cp -r /tmp/kylin-updateresult-notify.log updaterlog >/dev/null 2>&1 || true

    info "${BOLD}正在压缩日志...${NO_COLOR}"

    outputName="$(date +%m-%d-%H-%M-%S)-updaterLog.tar.gz"
    #将所有的日志进行打包
    tar -czvf updaterLog.tar.gz updaterlog >/dev/null

    #删除收集的日志目录
    rm -rf updaterlog

    #系统升级收集bug日志使用
    if [ $(id -u) -eq 0 ]; then
        mv updaterLog.tar.gz /tmp/$outputName
        info "${BOLD}请将日志文件提交到禅道,输出位置：${UNDERLINE}/tmp/$outputName${NO_COLOR}"
    else
        #将文件存储到桌面
        if [ ! -d ~/桌面 ]; then
            mv updaterLog.tar.gz ~/Desktop/$outputName
            info "${BOLD}请将桌面下日志文件提交到禅道,输出位置：${UNDERLINE}~/Desktop/$outputName${NO_COLOR}"
        else
            mv updaterLog.tar.gz ~/桌面/$outputName
            info "${BOLD}请将桌面下日志文件提交到禅道,输出位置：${UNDERLINE}~/桌面/$outputName${NO_COLOR}"
        fi
    fi
}

fn_apt_download() {
    if [ -f "/etc/kylin-system-updater/apt_private.conf" ]; then
        apt download $1 -c /etc/kylin-system-updater/apt_private.conf
	else
        apt download $1
    fi
}

fn_apt_install() {
    if [ -f "/etc/kylin-system-updater/apt_private.conf" ]; then
        sudo apt install --simulate $1 -c /etc/kylin-system-updater/apt_private.conf
	else
        sudo apt install --simulate $1
    fi
}

fn_update_problem() {
    error_desc="此错误目前不支持检查或系统更新存在异常。"
    solution="请联系系统更新研发，并上传日志。"

    arg_prompt_not_exit $error_desc $solution
}

fn_install_failed() {
    local end_time=$1
    append_dsc="详细错误日志查看/var/log/apt/term.log，简要错误描述："
    INSTALL_FAILED_SAFE="验证失败，拒绝安装"
    INSTALL_FAILED_SAFE_OTHER="未签名，拒绝安装"

    INSTALL_FAILED_SCRIPT="子进程返回错误状态"
    INSTALL_FAILED_SCRIPT_EN="script subprocess returned error"

    INSTALL_FAILED_INCLUDE="同时被包含于软件包"
    NSTALL_FAILED_INCLUDE_EN="which is also in package"

    SAFE_WHITELIST_FAILED="in the prevent uninstallation of whitelist!"

    term_msg=$(tac "$APT_TERM_LOG" | sed -n "/$end_time/,/Log started:/p" | tac )

    if [[ $term_msg == *"$INSTALL_FAILED_SAFE"* || $term_msg == *"$INSTALL_FAILED_SAFE_OTHER"* ]]; then        
        error_type="软件包验签失败或者未签名"
        solution="请联系安全事业部研发人员并且指派相应bug"
        error_desc=$(echo "$term_msg" | grep -E "$INSTALL_FAILED_SAFE|$INSTALL_FAILED_SAFE_OTHER")
        arg_prompt $error_type $solution "$append_dsc$error_desc"
    # 安装前后脚本执行错误
    elif [[ $term_msg == *"$INSTALL_FAILED_SCRIPT"* || $term_msg == *"$INSTALL_FAILED_SCRIPT_EN"* ]]; then
        # 获取安装错误的包
        error_pkg=$(echo "$term_msg" | grep -E "$INSTALL_FAILED_SCRIPT|$INSTALL_FAILED_SCRIPT_EN" | awk '{print $2}')
        error_type="软件包安装前后脚本执行错误，错误软件包："$error_pkg""
        maintainer=$(zcat /usr/share/doc/$error_pkg/changelog.Debian.gz | grep -m 1 '^ -- ' | awk -F' -- ' '{print $2}' | awk '{print $1, $2}')
        solution="请蓝信联系上述的包维护人("$maintainer")，并提交相应bug"
        error_desc=$(echo "$term_msg" | grep -E -B 5 "$INSTALL_FAILED_SCRIPT|$INSTALL_FAILED_SCRIPT_EN")

        arg_prompt "$error_type" "$solution" "$append_dsc$error_desc"
    elif [[ $term_msg == *"$INSTALL_FAILED_INCLUDE"* || $term_msg == *"$NSTALL_FAILED_INCLUDE_EN"* ]]; then
        # 获取安装错误的包
        error_pkg=$(echo "$term_msg" | grep -E "$INSTALL_FAILED_INCLUDE|$NSTALL_FAILED_INCLUDE_EN" | awk -F'软件包 ' '{print $2}' | awk '{print $1}')
        error_type="两个软件包包含相同文件，错误软件包："$error_pkg""
        maintainer=$(zcat /usr/share/doc/$error_pkg/changelog.Debian.gz | grep -m 1 '^ -- ' | awk -F' -- ' '{print $2}' | awk '{print $1, $2}')
        solution="请蓝信联系上述的软件包维护人("$maintainer")，并提交相应bug"
        error_desc=$(echo "$term_msg" | grep -E -B 1 "$INSTALL_FAILED_INCLUDE|$NSTALL_FAILED_INCLUDE_EN")

        arg_prompt "$error_type" "$solution" "$append_dsc$error_desc"
    elif [[ $term_msg == *"$SAFE_WHITELIST_FAILED"* ]]; then
        error_type="软件包在禁止卸载白名单"
        solution="请联系安全事业部研发人员并且指派相应bug"
        error_desc=$(echo "$term_msg" | grep "$SAFE_WHITELIST_FAILED")
        arg_prompt $error_type $solution "$append_dsc$error_desc"
    else
        fn_update_problem
    fi
}

fn_install_failed_other() {
    INSTALL_FAILED_SAFE="验证失败，拒绝安装！"
    INSTALL_FAILED_SAFE_OTHER="未签名，拒绝安装！"

    INSTALL_FAILED_SCRIPT="子进程返回错误状态"
    INSTALL_FAILED_SCRIPT_EN="script subprocess returned error"

    INSTALL_FAILED_INCLUDE="同时被包含于软件包"
    NSTALL_FAILED_INCLUDE_EN="which is also in package"

    SAFE_WHITELIST_FAILED="in the prevent uninstallation of whitelist!"

    term_msg=$(tac "$APT_TERM_LOG" | awk '/Log ended:/,/Log started:/ {if ($0 ~ /Log started:/ && !found) found=1; if (!found) print}' | tac)

    if [[ $term_msg == *"$INSTALL_FAILED_SAFE"* || $term_msg == *"$INSTALL_FAILED_SAFE_OTHER"* ]]; then
        echo "$term_msg" | grep -E "$INSTALL_FAILED_SAFE|$INSTALL_FAILED_SAFE_OTHER"
        exit 0
    # 安装前后脚本执行错误
    elif [[ $term_msg == *"$INSTALL_FAILED_SCRIPT"* || $term_msg == *"$INSTALL_FAILED_SCRIPT_EN"* ]]; then
        echo "$term_msg" | grep -E -B 5 "$INSTALL_FAILED_SCRIPT|$INSTALL_FAILED_SCRIPT_EN"
        exit 0
    elif [[ $term_msg == *"$INSTALL_FAILED_INCLUDE"* || $term_msg == *"$NSTALL_FAILED_INCLUDE_EN"* ]]; then
        echo "$term_msg" | grep -E -B 1 "$INSTALL_FAILED_INCLUDE|$NSTALL_FAILED_INCLUDE_EN"
        exit 0
    elif [[ $term_msg == *"$SAFE_WHITELIST_FAILED"* ]]; then
        echo "$term_msg" | grep -B 1 "$SAFE_WHITELIST_FAILED"
        exit 0
    else
        echo "无法识别或者没有错误"
    fi
}

fn_install_failed_easy() {
    INSTALL_FAILED_SAFE="验证失败，拒绝安装！"

    INSTALL_FAILED_SCRIPT="子进程返回错误状态"
    INSTALL_FAILED_SCRIPT_EN="script subprocess returned error"

    INSTALL_FAILED_INCLUDE="同时被包含于软件包"

    SAFE_WHITELIST_FAILED="in the prevent uninstallation of whitelist!"

    term_msg=$(tac "$APT_TERM_LOG" | awk '/Log ended:/,/Log started:/ {if ($0 ~ /Log started:/ && !found) found=1; if (!found) print}' | tac)

    if [[ $term_msg == *"$INSTALL_FAILED_SAFE"* ]]; then
        echo "验证失败，拒绝安装"
        exit 0
    # 安装前后脚本执行错误
    elif [[ $term_msg == *"$INSTALL_FAILED_SCRIPT"* || $term_msg == *"$INSTALL_FAILED_SCRIPT_EN"* ]]; then
        echo "安装前后脚本执行错误"
        exit 0
    elif [[ $term_msg == *"$INSTALL_FAILED_INCLUDE"* ]]; then
        echo "两个软件包同时包含相同文件"
        exit 0
    elif [[ $term_msg == *"$SAFE_WHITELIST_FAILED"* ]]; then
        echo "卸载白名单"
        exit 0
    else
        echo "无法识别或者没有错误"
    fi    
}

fn_self_depends() {
# 优先升级依赖问题

    echo ""
}

fn_check_update_source() {
    # 检查是否采用A/B源机制
    # 检查离线源deb file:
    
    if [ "$OFFLINE_SOURCE_FLAG" = "$TRUE" ]; then
        if [ -e "$OFFLINE_SOURCE_PATH" ]; then
            if [ -n "$(ls -A "$OFFLINE_SOURCE_PATH")" ]; then
                echo ""
            else
                arg_prompt "离线源被卸载，可能由于关闭控制面板或者其他原因。" "需要重新挂载离线源，再进行更新"                
            fi
        else
            arg_prompt "离线源被卸载，可能由于关闭控制面板或者其他原因。" "需要重新挂载离线源，再进行更新"
        fi
    fi

    info "${BOLD}进行apt update测试，等待时间5分钟之内请稍后...${NO_COLOR}"
    if [ -f "/etc/kylin-system-updater/apt_private.conf" ]; then
        append_desc=$(LANG= sudo timeout 5s apt update -c /etc/kylin-system-updater/apt_private.conf 2>&1)
	else
        append_desc=$(LANG= sudo timeout 5s apt update 2>&1)
    fi

    if [ $? -eq 0 ]; then
        fn_update_problem
    elif [ $? -eq 124 ]; then
        error_desc="检查更新 apt update 执行超时"
        solution="1、请检查网络是否正常； 2、检查是否开启限速"
    else
        if [[ $append_desc == *"invalid for another"* ]]; then
            error_desc="检查更新apt update失败，未校准时间"
            solution="请校准时间再进行系统更新。"
        else
            error_desc="软件源更新apt update更新失败"
            solution="检查：1.使用的源是否正确，2.检查host的配置。若其他设备都存在问题，则联系版本组检查源"
        fi
    fi

    arg_prompt "$error_desc" "$solution" "$append_desc"
}

fn_check_latest() {
    # 检查推送文件是否存在
    append_desc=""
    append_other="，若配置没问题请联系源管理研发。。"
    if ! [ -f "$SOURCES_LIST" ]; then
        error_desc="系统更新源不存在:$SOURCES_LIST"
        solution="请检查是否导入序列号，并且在源管理服务端推送内容$append_other"
    elif [ -f "/var/lib/kylin-software-properties/template/important.list" ]; then
        # 检查内容是否为空
        if [ -s "/var/lib/kylin-software-properties/template/important.list" ]; then
            append_other=$(cat /var/lib/kylin-software-properties/template/important.list)

            fn_update_problem
        else
            error_desc="推送内容为空。"
            solution="请检查是否导入序列号，并且在源管理服务端推送内容$append_other"
        fi
    elif ! [ -f "/var/lib/kylin-software-properties/template/important.list" ]; then
        error_desc="没有推送内容文件。"
        solution="请检查是否导入序列号$append_other"
    else
        fn_update_problem
    fi
    arg_prompt "$error_desc" "$solution" "$append_desc"
}

fn_check_config_depends() {

    echo "错误描述:配置软件包kylin-update-desktop-config无法安装，软件源中不存在此包"
    echo ""
    echo "开始检查config包是否在源内"

    fn_apt_install  kylin-update-desktop-config

    if [ $? -eq 0 ]; then
        fn_update_problem
    else
        echo "发现错误，未发现config在源内，请检查使用的源是否正确，或者推送是否正确"
        echo "若还是无法解决，请联系版本组解决"
    fi
}

fn_check_download_pkgs() {
    search_string="Hashes of received file"
    match_line=$(grep -n "$search_string" "$UPDATER_LOG_PATH" | head -n 1 | cut -d ":" -f 1)

    # 如果找到匹配的行
    if [ -n "$match_line" ]; then
        # 输出匹配内容上下10行的内容
        echo "发现下面错误信息:"
        echo ""
        tail -n +$((match_line - 8)) "$UPDATER_LOG_PATH" | head -n 17

        echo "请联系版本组检查离线源或者在线源内容"
    else
        echo "当前使用在线源更新方式，测试下载软件包从源中"
        fn_apt_download kylin-system-updater
        if [ $? -eq 0 ]; then
            rm *kylin-system-updater*.deb
            echo "下载软件包正常，导出系统更新日志到禅道"
        else
            if ! [ "$OFFLINE_SOURCE_FLAG" = "$TRUE" ]; then
                echo "测试下载失败，检查网络连接，网络连接完善后使用apt download tree 软件包测试是否正常"
            else
                echo "测试下载失败，联系版本组检查离线源是否正常"
            fi
        fi
    fi
}

fn_check_source_manager() {
    info "${BOLD}进行刷新源测试，最长时间30s请稍后...${NO_COLOR}"
    local append_desc=$(timeout 20s kylin-source-update 2>&1)

    if [ $? -eq 0 ]; then
        if [[ $append_desc == *"true"* ]]; then
            fn_update_problem
        else
            error_desc="源管理客户端刷新源失败"
            solution="检查设备网络是否正常，无法解决时请联系源管理研发人员。"
        fi
    elif [ $? -eq 124 ]; then
        error_desc="源管理客户端刷新源超时。"
        solution="1、请检查网络是否正常，无法解决时请联系源管理研发人员。"
    else
        error_desc="源管理客户端刷新源超时。"
        solution="1、请检查网络是否正常，无法解决时请联系源管理研发人员。"
    fi
    arg_prompt "$error_desc" "$solution" "$append_desc"
}

fn_check_version() {
    version_check_flag="Version Check Desc:"
    customized_path_flag="Customized patch: "
    intermediate_path_flag="Version mismatch "

    error_desc=$(tac $UPDATER_LOG_PATH | grep -m 1 "$version_check_flag" | awk -F "$version_check_flag" '{print $2}')
    solution="联系版本组校对版本与补丁匹配数据库，并提交相应bug"

    append_desc=$(tac $UPDATER_LOG_PATH | grep -E -m 1 "$intermediate_path_flag|$customized_path_flag")
    if [[ $append_desc == *$customized_path_flag* ]]; then
        append_desc="定制源：$(echo $append_desc | awk -F "$customized_path_flag" '{print $2}')"
    elif [[ $append_desc == *$intermediate_path_flag* ]]; then
        append_desc="不在包版本数据库的包列表：$(echo $append_desc | awk -F "$intermediate_path_flag" '{print $2}')"
    else
        append_desc="无法识别详细错误，查看系统更新日志"
    fi
    arg_prompt "$error_desc" "$solution" "$append_desc"
}

fn_check_remove_essential() {

    version_check_flag="Essential Packages"
    delete_flag="DELETE_DETAILS"
    error_desc=$(tac $UPDATER_LOG_PATH | grep -m 1 "$version_check_flag" | awk -F "$version_check_flag" '{print $2}')
    error_desc="被删除的重要软件包：$error_desc"
    solution="联系版本组检查此包是否可以被卸载，若可以删除则在config包install_list列表中删除此包，删除原因查看系统更新日志，检索DELETE_DETAILS字符。"
    
    append_desc=$(tac $UPDATER_LOG_PATH | grep -m 5 "$delete_flag" | awk -F "$delete_flag" '{print $2}')
    append_desc="被软件包原因：$append_desc"
    arg_prompt "$error_desc" "$solution" "$append_desc"
}

fn_download_deb_failed() {
    msg=$(tac "$UPDATER_LOG_PATH" | grep -m 2 'Failed to fetch')
    error_desc="软件包下载失败。"
    solution="检查网络是否正常，若正常测试其他设备是否也有相同问题，都存在问题时联系版本组或者平台组检查源"

    arg_prompt "$error_desc" "$solution" "$msg"
}

fn_check_remove_pkg() {

    delete_check_flag="UpdateDependResloveStatus:resolver_status = True , remove_status = True , remove_pkgs ="
    delete_flag="DELETE_DETAILS"

    error_desc=$(tac $UPDATER_LOG_PATH | grep -m 1 "$delete_check_flag" | grep -o 'remove_pkgs = [^ ]*,')
    error_desc="被删除的软件包：$error_desc"
    solution="联系版本组检查此包是否可以被卸载，若可以删除则在config包remove_white_list列表中删除此包，删除原因查看系统更新日志，检索DELETE_DETAILS字符。"
    
    append_desc=$(tac $UPDATER_LOG_PATH | grep -m 5 "$delete_flag" | awk -F "$delete_flag" '{print $2}')
    append_desc="被软件包原因：$append_desc"
    arg_prompt "$error_desc" "$solution" "$append_desc"
}

fn_check_broken_pkg() {
    error_desc="系统软件包环境破损"
    solution="确认自己是否dpkg或者apt安装过软件包并且存在报错，若不存在则联系-系统更新研发处理"
    append_desc=$(apt install -f --simulate)
    arg_prompt "$error_desc" "$solution" "$append_desc"
}

fn_check_network() {
    error_desc="网络检查失败。"
    solution="请检查是否正常连接网络"
    arg_prompt "$error_desc" "$solution"
}

fn_time_compare() {
    input_date=$1

    # 获取当前年份
    current_year=$(date +%Y)

    # 把给定的日期转换为包含当前年份的日期格式
    input_date_full="$current_year-$input_date"

    # 获取当前日期和两天前的日期（使用日期格式 %Y-%m-%d）
    current_date=$(date +%Y-%m-%d)
    two_days_ago=$(date -d "-10 days" +%Y-%m-%d)

    # 转换日期为秒数以便比较
    input_date_seconds=$(date -d "$input_date_full" +%s)
    current_date_seconds=$(date -d "$current_date" +%s)
    two_days_ago_seconds=$(date -d "$two_days_ago" +%s)

    # 比较日期
    if [[ "$input_date_seconds" -ge "$two_days_ago_seconds" && "$input_date_seconds" -le "$current_date_seconds" ]]; then
        local ttt=tt
    else
        fn_update_problem
    fi
}

main() {
    while :; do
        case $1 in
            -h|-\?|--help)
                fn_display_usage
                exit
                ;;
            -f|--install-failed)
                shift
                fn_install_failed_other
                exit 0
                ;;
            -f|--install-failed-easy)
                shift
                fn_install_failed_easy
                exit 0
                ;;
            *)
                break
        esac

        shift
    done

    # 提取日志最后的错误信息进行分析
    bug_msg=$(tac "$UPDATER_LOG_PATH" | grep -m 1 'UpdateDependResloveStatus:resolver_status = False \|UpdateDependResloveStatus:resolver_status = True , remove_status = True \|UpdateDetectFinished success = False \|UpdateDownloadFinished success = False \|UpdateInstallFinished success = False \|ForceUpdatePopup success = True \|UpdateDetectFinished success = True , upgrade_group = \[\]')

    current_year=$(date +%Y)
    month_day=${bug_msg:0:5}
    hours=${bug_msg:6:6}

    # 限制错误扫描的时间在两天之内
    fn_time_compare $month_day

    ERROR_DESC=$(echo "$bug_msg"  | grep -o 'error_desc = [^ ]*' | sed 's/error_desc = //')
    ERROR_STR=$(echo "$bug_msg"  | grep -o 'error_string = [^ ]*' | sed 's/error_string = //')

    if ! [ -z "$ERROR_DESC" ]; then
        pass=pass
    elif [[ $bug_msg == *"UpdateDetectFinished success = True , upgrade_group = []"* ]]; then
        ERROR_DESC="您的系统已是最新"
    elif [[ $bug_msg == *"ForceUpdatePopup success = True"* ]]; then
        ERROR_DESC="版本与补丁校验不匹配。"
    elif [[ $bug_msg == *"UpdateDependResloveStatus:resolver_status = True , remove_status = True"* ]]; then
        ERROR_DESC="依赖冲突，需要卸载软件包。"
    else
        if [[ "$0" == *"/usr/share/kylin-system-updater/scripts/"* ]]; then
            exit 0
        else
            fn_update_problem
        fi
    fi
    
    case $ERROR_DESC in
        无法安装或移除软件包。|安装或移除软件包失败。)
            ERROR_DESC="$ERROR_DESC错误码：#0200"
            fn_install_failed "Log ended: $current_year-$month_day  $hours"
            ;;
        无法访问源管理服务器，请稍后再试)
            ERROR_DESC="$ERROR_DESC错误码：#0100"
            fn_check_source_manager
            ;;
        无法下载软件仓库信息，检查您的网络连接。|检查您的网络连接。|无法下载软件仓库信息)
            case $ERROR_STR in
                无法下载软件包文件|下载软件包文件失败)
                    ERROR_DESC="$ERROR_DESC错误码：#0203"
                    fn_download_deb_failed
                    ;;
                无法下载软件仓库信息|检查更新异常！)
                    ERROR_DESC="$ERROR_DESC错误码：#0115"
                    fn_check_update_source
                    ;;
                *)
                    fn_update_problem
            esac
            ;;
        您的系统已是最新)
            ERROR_DESC="$ERROR_DESC(需要进行系统更新但一直提示最新情况)"
            fn_check_latest
            ;;
        请检查您的网络连接后再试。)
            fn_check_network
            ;;
        版本与补丁校验不匹配。)
            ERROR_DESC="$ERROR_DESC错误码：#0117"
            fn_check_version
            ;;
        \#0202)
            ERROR_DESC="您要求删除一个系统必要的软件包。错误码：#0202"
            fn_check_remove_essential
            ;;
        依赖冲突，需要卸载软件包。)
            fn_check_remove_pkg
            ;;
        这是个很严重的问题。请稍后重试。如果问题还出现，请向开发人员报告一个错误。)
            fn_check_broken_pkg
            ;;
        # 无法安装组配置包，请检查组配置包相关依赖。)
        #     fn_check_config_depends
        #     ;;
        # 本次更新无法检测到可升级的软件包。)
        #     fn_check_overall
        #     ;;
        # 无法进行优先升级，请检查优先升级包相关依赖。)
        #     fn_self_depends
        #     ;;
        *)
            fn_update_problem
    esac
}

main "$@"

